/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.scripting.impl.js;

import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.support.scripting.CompliableScriptEngine;
import cn.easyplatform.support.scripting.RhinoScriptable;
import cn.easyplatform.support.scripting.ScriptCmdContext;
import cn.easyplatform.support.scripting.ScriptUtils;
import cn.easyplatform.support.scripting.cmd.MainCmd;
import org.mozilla.javascript.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RhinoCompliableScriptEngine implements CompliableScriptEngine {

    private final static Logger log = LoggerFactory.getLogger(RhinoCompliableScriptEngine.class);

    private RhinoScriptable scope;

    private Script scriptEval;

    private CommandContext cc;

    private MainCmd cmd;

    @Override
    public CompliableScriptEngine compile(CommandContext cc, String script) {
        script = ScriptUtils.parse(cc, cc.getWorkflowContext().getRecord(), script.trim());
        if (cc.getUser().isDebugEnabled())
            cc.send("script:" + script);
        else
            log.debug("script:" + script);
        this.cc = cc;
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            scope = new RhinoScriptable();
            scope.initStandardObjects(cx, false);
            cmd = ScriptUtils.createVariables(scope, cc,
                    cc.getWorkflowContext());
            // 准备内嵌的函数
            cx.evaluateString(scope, RhinoScriptEngine.functions, "", 1, null);
            scriptEval = cx.compileString(script, "", 1, null);
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
        }
        return this;
    }

    @Override
    public CompliableScriptEngine compile(ScriptCmdContext ctx, String script,
                                          RhinoScriptable scope) {
        this.cc = ctx.getCommandContext();
        this.cmd = (MainCmd) ctx;
        script = ScriptUtils.parse(cc, cc.getWorkflowContext().getRecord(), script.trim());
        if (log.isDebugEnabled())
            log.debug("eval->{}", script);
        if (cc.getUser().isDebugEnabled())
            cc.send("script:" + script);
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(9);
            this.scope = new RhinoScriptable(scope.getScope());
            this.scope.initStandardObjects(cx, false);
            scriptEval = cx.compileString(script, "", 1, null);
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
        }
        return this;
    }

    @Override
    public Object eval(RecordContext... rcs) {
        if (rcs.length > 0) {
            cmd.setData(rcs);
            // cc.send(I18N.getLable("script.engine.system.var", cmd.getTarget()
            // .getSystemVars()));
            // cc.send(I18N.getLable("script.engine.user.var", "onBatch"));
            // cc.send(cmd.getTarget().getUserVars());
            // cc.send(I18N.getLable("script.engine.field.var", "onBatch"));
            // cc.send(cmd.getTarget().getRecordFieldValues());
        }
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(9);
            Object result = scriptEval.exec(cx, scope);
            // if (rcs.length > 0) {
            // cc.send(I18N.getLable("script.engine.system.var", cmd
            // .getTarget().getSystemVars()));
            // cc.send(I18N.getLable("script.engine.user.var", "onBatch"));
            // cc.send(cmd.getTarget().getUserVars());
            // cc.send(I18N.getLable("script.engine.field.var", "onBatch"));
            // cc.send(cmd.getTarget().getRecordFieldValues());
            // }
            if (result instanceof Wrapper)
                result = ((Wrapper) result).unwrap();
            return result instanceof Undefined ? null : result;
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
        }
    }

    @Override
    public RhinoScriptable getScope() {
        return scope;
    }

    @Override
    public void destroy() {
        if (scope != null) {
            scope.clear();
            scope = null;
            scriptEval = null;
        }
        cmd = null;
    }
}
